package com.example.icongyou.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.icongyou.R;
import com.example.icongyou.adapter.TeamMemberAdapter;
import com.example.icongyou.api.TeamApi;
import com.example.icongyou.bean.Team;
import com.example.icongyou.bean.TeamDashboardBean;
import com.example.icongyou.bean.TeamMember;
import com.example.icongyou.retrofit.RetrofitClient;

import java.util.List;
import java.util.stream.Collectors;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 团队数据看板碎片：展示团队得分、排名、成员贡献度
 */
public class TeamDashboardFragment extends Fragment {

    // 控件声明
    private TextView tvTeamName;
    private TextView tvTeamScore;
    private TextView tvTeamRank;
    private RecyclerView rvTeamMembers;
    private TeamMemberAdapter memberAdapter;

    // 团队ID（实际项目中从登录信息或前序页面获取）
    private String teamId = "1"; // 需替换为真实团队ID获取逻辑

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_team_dashboard, container, false);
        initViews(view);
        loadTeamData(); // 加载真实接口数据
        return view;
    }

    /**
     * 初始化所有控件
     */
    private void initViews(View view) {
        tvTeamName = view.findViewById(R.id.tv_team_name);
        tvTeamScore = view.findViewById(R.id.tv_team_score);
        tvTeamRank = view.findViewById(R.id.tv_team_rank);
        rvTeamMembers = view.findViewById(R.id.rv_team_members);

        rvTeamMembers.setLayoutManager(new LinearLayoutManager(getContext()));
        rvTeamMembers.setHasFixedSize(true);
    }

    /**
     * 加载团队数据（对接后端接口）
     */
    // 加载团队数据（对接后端接口）
    private void loadTeamData() {
        // 1. 获取TeamApi实例
        TeamApi teamApi = RetrofitClient.getTeamApi(); // 确保RetrofitClient中有getTeamApi()方法

        // 2. 发起网络请求（使用新的接口方法）
        // 注意：需要将teamId转换为Long类型（根据你的实际teamId获取方式调整）
        try {
            Long teamIdLong = Long.parseLong(teamId);
            teamApi.getTeamDashboard(teamIdLong).enqueue(new Callback<TeamDashboardBean>() {
                @Override
                public void onResponse(Call<TeamDashboardBean> call, Response<TeamDashboardBean> response) {
                    if (response.isSuccessful() && response.body() != null) {
                        TeamDashboardBean dashboardBean = response.body();
                        updateTeamUI(dashboardBean); // 适配新的数据模型
                    } else {
                        Toast.makeText(getContext(), "获取团队数据失败：" + response.message(), Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<TeamDashboardBean> call, Throwable t) {
                    Toast.makeText(getContext(), "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
        } catch (NumberFormatException e) {
            Toast.makeText(getContext(), "团队ID格式错误", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }


    /**
     * 更新团队看板UI（逻辑不变，复用原有代码）
     */
    private void updateTeamUI(TeamDashboardBean dashboard) {
        if (dashboard == null) {
            Toast.makeText(getContext(), "团队数据加载失败", Toast.LENGTH_SHORT).show();
            return;
        }

        // 更新团队基本信息
        tvTeamName.setText(dashboard.getTeamName());
        tvTeamScore.setText(String.format("%.1f", dashboard.getTeamScore()));
        tvTeamRank.setText(String.format("第%d名", dashboard.getTeamRanking()));

        // 更新成员列表（需要将ContributionItem转换为TeamMember或直接适配适配器）
        if (dashboard.getContributions() != null) {
            // 如果TeamMemberAdapter需要TeamMember类型，这里需要转换
            List<TeamMember> teamMembers = dashboard.getContributions().stream()
                    .map(item -> {
                        TeamMember member = new TeamMember();
                        member.setStudentId(String.valueOf(item.getStudentId()));
                        member.setStudentName(item.getStudentName());
                        member.setRole(item.getRole());
                        member.setContribution(item.getContributionRate()); // 贡献度百分比
                        return member;
                    })
                    .collect(Collectors.toList());

            memberAdapter = new TeamMemberAdapter(teamMembers);
            rvTeamMembers.setAdapter(memberAdapter);
        }
    }
}